package com.hodge.core.result;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hodge.core.enums.ResultCode;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.experimental.Accessors;
import org.springframework.util.CollectionUtils;

import java.util.Collections;
import java.util.List;
import java.util.Objects;

/**
 * 统一返回体
 *
 * @author haojun
 * @since 2020/3/18 18:50
 */
@Data
@Accessors(chain = true)
@NoArgsConstructor
@AllArgsConstructor
public class Result {
    /**
     * 状态码
     */
    private ResultCode code;
    /**
     * 状态说明
     */
    private String message;
    /**
     * 错误信息
     */
    private String exception;
    /**
     * 数据
     */
    private List<?> data;
    /**
     * 总条数
     */
    private Long total;
    /**
     * 当前页
     */
    private Long index;
    /**
     * 页大小
     */
    private Long limit;

    public Result(ResultCode code) {
        this.code = code;
        this.message = code.getMsg();
    }

    public static Result withData(Page<?> data) {
        return code(ResultCode.SUCCESS)
                .setData(data.getRecords())
                .setIndex(data.getCurrent())
                .setLimit(data.getSize())
                .setTotal(data.getTotal());
    }

    public static Result withData(List<?> data) {
        return code(ResultCode.SUCCESS)
                .setData(CollectionUtils.isEmpty(data) ? Collections.emptyList() : data)
                .setTotal((long) data.size());
    }

    public static Result withData(Object data) {
        List<Object> list = Objects.isNull(data) ? Collections.emptyList() : Collections.singletonList(data);
        return code(ResultCode.SUCCESS)
                .setData(list)
                .setTotal((long) list.size());
    }

    public static Result success() {
        return code(ResultCode.SUCCESS);
    }

    public static Result failure() {
        return code(ResultCode.FAILURE);
    }

    public Result setCode(ResultCode code) {
        this.code = code;
        this.message = code.getMsg();
        return this;
    }

    public static Result code(ResultCode code) {
        return new Result().setCode(code);
    }

    public String toJsonString(){
        return JSON.toJSONString(this);
    }
}
